<?php
declare (strict_types=1);

namespace app\admin\controller;

use app\BaseController;
use app\common\tool\Result;
use think\exception\ValidateException;
use addons\BuilderPlus\components\Compress;

class Uploads extends BaseController
{
    public function __call($name, $arguments)
    {
        try {
            $file = $this->request->file();
            $action = $name;
            if ($name == 'editor') {
                if (!empty($file['wangeditor-uploaded-video'])) {
                    $file['file'] = $file['wangeditor-uploaded-video'];
                    $action = 'video';
                } else {
                    $action = 'image';
                }
            }
            $config = config('tool')['upload'][$action];
            if (empty($config)) throw new \Exception('配置文件错误');
            $this->validate($file,
                [
                    'file' => "fileSize:{$config['fileSize']}|fileExt:{$config['fileExt']}"
                ],
                [
                    'file.fileSize' => '文件大小不得超过' . (intval($config['fileSize']) / 1024 / 1024) . 'M',
                    'file.fileExt' => "文件格式错误，请上传{$config['fileExt']}格式文件"
                ]
            );

            return Result:: fastReturn((new Compress($config))->$action($file));
        } catch (ValidateException $e) {

            return Result::fail($e->getError());
        } catch (\Exception $e) {

            return Result::fail($e->getMessage());
        }
    }
}